package org.aeon.newsmanagersystem.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.aeon.newsmanagersystem.annotation.Protected;
import org.aeon.newsmanagersystem.pojo.NewsUsers;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author: MissingAeon
 * @date: 2024/3/29 15:36
 * @description:
 */
public class PermissionsInterceptor implements HandlerInterceptor {
    // 处理前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final HttpSession session = request.getSession();
        final NewsUsers user = (NewsUsers) session.getAttribute("user");

        if (handler instanceof HandlerMethod) {
            final Protected annotation = ((HandlerMethod) handler).getMethodAnnotation(Protected.class);
            if (annotation != null) {
                if (user != null) {
                    return user.getUrole() == 2;
                }
                final String contextPath = request.getContextPath();
                final String encodedText = URLEncoder.encode("权限不足", StandardCharsets.UTF_8);
                response.sendRedirect(contextPath + "/error?text=" + encodedText);
                return false;
            }
        }
        return true;
    }
}
